home *** CD-ROM | disk | FTP | other *** search
/ Celestin Apprentice 4 / Apprentice-Release4.iso / Source Code / C / Snippets / getopt / getopt.c next >
Encoding:
C/C++ Source or Header  |  1996-01-03  |  1.1 KB  |  40 lines  |  [TEXT/R*ch]

  1. #include <stdlib.h>
  2. #include <string.h>
  3. #include <stdio.h>
  4. #include "getopt.h"
  5.  
  6. char *optarg;
  7. int optind = 1, opterr = 1;
  8.  
  9. int getopt(int argc, char *argv[], char *optstring)
  10. {
  11.         char *argvstr = argv[optind];
  12.         char *optpos;
  13.  
  14.         if ((optind >= argc) ||
  15.                 (!strcmp(argvstr, "--")))
  16.                 return -1;
  17.         else {
  18.                 optind++;
  19.                 if (*argvstr != '-')
  20.                         return getopt(argc, argv, optstring);
  21.                 else
  22.                         argvstr++;
  23.                 if (*argvstr == '\0')
  24.                     return '?';
  25.                 optpos = strchr(optstring, *argvstr);
  26.                 if (optpos == NULL)     {
  27.                         if (opterr) fprintf(stderr, "Incorrect command-line options.\n");
  28.                         return '?';
  29.                 }
  30.                 optpos++;
  31.                 if (*optpos     == ':') {
  32.                         if (optind >= argc)
  33.                                 return '?';
  34.                         optarg = argv[optind];
  35.                         optind++;
  36.                 }
  37.                 return (*argvstr);
  38.         }
  39. }
  40.